<%@page import="com.client.service.CpUserDataServiceImpl"%>
<%@page import="com.client.service.CpUserDataService"%>
<%@page import="com.client.model.ICpUserData"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="com.utils.dbcp.ModelGenerator"%>
<%@page import="com.manage.config.Config"%>
<%@page import="com.util.ConfigUtil"%>
<%@page import="com.client.model.IUserData"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.manage.service.SyncConfigServiceImpl"%>
<%@page import="com.manage.service.SyncConfigService"%>
<%@ page contentType="text/html;charset=utf-8"%>
<%@page import="com.manage.model.SyncConfig"%>
<%@page import="java.util.List"%>
<%!

/*
  <servlet>
    <servlet-name>UserDataSyncServlet</servlet-name>
    <jsp-file>/servlet/UserDataSyncServlet.jsp</jsp-file>
    <load-on-startup>1</load-on-startup>
  </servlet>
*/

public void jspInit()
{
  running = true;
  thread = new SyncThread();
  thread.start();
}

public void jspDestory()
{
	running = false;
	thread.interrupt();
}

private boolean running = false;
private SyncThread thread;

class SyncThread extends Thread
{
	public void run()
	{
		while (!currentThread().isInterrupted() 
				&& running)
		{
			try
			{
				 Calendar calendar = Calendar.getInstance();           
				if(3 == calendar.get(Calendar.HOUR_OF_DAY)&&calendar.get(Calendar.MINUTE) < 10)
				{
					//读取同步配置
					SyncConfigService service  = new SyncConfigServiceImpl();
					List<SyncConfig> syndlist = service.getSyncConfigs();
					
					//查询前一天的数据
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		            Calendar cal = Calendar.getInstance();
		            cal.add(Calendar.DATE, -1); 
		            int day = Integer.parseInt(sdf.format(cal.getTime()));
		            //id,day,hour,minute,plugin,channel,project,province,region,count,newcount
		            String dbcp = ConfigUtil.get(Config.SECTION, Config.KEY_DBCP_NAME);
		            String sql = "select id,day,0 hour,0 minute,0 plugin,channel,0 project,0 province,0 region,0 count,sum(newcount) newcount from userdata where day = "+day+" group by channel,day" ;
		            ModelGenerator<IUserData> mg = new ModelGenerator<IUserData>(
							IUserData.class);
		            List<IUserData> luserdata = mg.generateList(dbcp, sql);
					//根据配置进行分析
					//存放每个渠道每天的总量
					Map<String,Integer> cnummap = new HashMap<String,Integer>();
					//存放每个渠道每天的百分比
					Map<String,Integer> cbfb = new HashMap<String,Integer>();
					if(luserdata!=null && luserdata.size()>0)
					{
						//计算每天每个渠道的总量
						for(int i =0;i<luserdata.size();i++)
						{
							IUserData iud = luserdata.get(i);
							if(cnummap.get(""+iud.getChannel())!=null)
							{
								cnummap.put(""+iud.getChannel(),(cnummap.get(""+iud.getChannel())+iud.getNewcount()));
							}else
							{
								cnummap.put(""+iud.getChannel(),iud.getNewcount());
							}
						}
						System.out.println("cnummap::::"+cnummap.toString());
						//计算每个渠道的总量是否超出设置的日限和总限,算出真实的扣百分比，保证百分比之后不超出设置的日总量
						for(int j =0;j<syndlist.size();j++)
						{
							SyncConfig sync = syndlist.get(j);
							if(cnummap.get(""+sync.getChannelid())!=null)
							{
								int cpdaycount = cnummap.get(""+sync.getChannelid());
								if(sync.getDayratio()>-1)
								{
									cpdaycount = (int)(Float.parseFloat(""+cpdaycount)/Float.parseFloat("100")*Float.parseFloat(""+sync.getDayratio()));
								}
								//-1不限制
								if(sync.getDaylimit()!=-1 && cpdaycount >sync.getDaylimit())
								{
									int ratio = 0;
									float a = (Float.parseFloat(""+cnummap.get(""+sync.getChannelid()))-Float.parseFloat(""+sync.getDaylimit()))/Float.parseFloat(""+cnummap.get(""+sync.getChannelid()))*100;
									System.out.print("计算超量的百分比");
									if(sync.getDayratio()!=-1)
									{
										if(sync.getDayratio()-(int)a>0)
										{
											ratio = sync.getDayratio()-(int)a;
										}
									}
									else
									{
										ratio = 100-(int)a;
									}
									cbfb.put(""+sync.getChannelid(),ratio);
								}
								else
								{
									if(sync.getDayratio()>-1)
										cbfb.put(""+sync.getChannelid(),sync.getDayratio());
									
								}
							}
						}
						System.out.println("hi:"+cbfb.toString());
						
						CpUserDataService cpservice = new CpUserDataServiceImpl();
						//插入到CP表中
						for(int i =0;i<luserdata.size();i++)
						{
							IUserData iud = luserdata.get(i);
							//根据之前计算的比例，计算出真实的CP用户数
							int usercount = 0;
							if(cbfb.get(""+iud.getChannel())!=null && cbfb.get(""+iud.getChannel())>=0)
							{
								usercount =(int) (Float.parseFloat(""+iud.getNewcount())/Float.parseFloat("100")*Float.parseFloat(""+cbfb.get(""+iud.getChannel())));
							}
							else
							{
								usercount = iud.getNewcount();
							}
							if(usercount==0)
							{
								continue;
							}
							//判断是否超总量
							String sqlcount = "select sum(newcount) from cpuserdata where channel = "+iud.getChannel()
							+" ";
			                ModelGenerator<Integer> mg1 = new ModelGenerator<Integer>(Integer.class);
							int totalcount = mg1.generate(dbcp, sqlcount);
							int tc = 0;
							for(int j =0;j<syndlist.size();j++)
							{
								if(iud.getChannel()==syndlist.get(j).getChannelid())
								{
									tc = syndlist.get(j).getTotallimit();
								}
							}
							
							if(tc>0 && (totalcount+usercount)>tc)
							{
								continue;
							}
							
							ICpUserData cpUserData = new ICpUserData();
							cpUserData.setChannel(iud.getChannel());
							cpUserData.setCount(iud.getCount());
							cpUserData.setDay(iud.getDay());
							cpUserData.setHour(iud.getHour());
							cpUserData.setId(-1);
							cpUserData.setMinute(iud.getMinute());
							cpUserData.setPlugin(iud.getPlugin());
							cpUserData.setProject(iud.getProject());
							cpUserData.setProvince(iud.getProvince());
							cpUserData.setRegion(iud.getRegion());
							cpUserData.setNewcount(usercount);
							cpservice.addCpUserData(cpUserData);
						}
						
					}
				}
	            sleep(10 * 60 * 1000L);
			}catch(Exception ex)
			{
				System.out.println("UserDateSyncServlet error:"+ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
}

%>
